package net.chasing.androidbaseconfig.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.TrafficStats;
import android.os.Handler;
import android.os.Message;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 发送what=100，obj=%.2fMb/s 或 %.2fKb/s 的Message
 */
public class NetWorkSpeedUtils {

    public static final int WHAT_NET_SPEED = 100;

    private final Context context;
    private Handler mHandler;
    private Timer mTimer;

    private long lastTotalRxBytes = 0;
    private long lastTimeStamp = 0;

    public NetWorkSpeedUtils(Context context, Handler mHandler) {
        this.context = context;
        this.mHandler = mHandler;
    }

    private final TimerTask task = new TimerTask() {
        @Override
        public void run() {
            showNetSpeed();
        }
    };

    public void cancel(){
        if (mTimer != null)
            mTimer.cancel();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

    public void startShowNetSpeed() {
        lastTotalRxBytes = getTotalRxBytes();
        lastTimeStamp = System.currentTimeMillis();
        mTimer = new Timer();
        mTimer.schedule(task, 1000, 1000);
    }

    private long getTotalRxBytes() {
        return TrafficStats.getUidRxBytes(context.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
    }

    @SuppressLint("DefaultLocale")
    private void showNetSpeed() {
        long nowTotalRxBytes = getTotalRxBytes();
        long nowTimeStamp = System.currentTimeMillis();
        float speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (float) (nowTimeStamp - lastTimeStamp));//毫秒转换   kb/s
        String speedStr;
        if (speed >= 1024) {
            speed /= 1024f;
            speedStr = String.format("%.2fMb/s", speed);
        } else
            speedStr = String.format("%.2fKb/s", speed);

        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;

        Message msg = mHandler.obtainMessage();
        msg.what = WHAT_NET_SPEED;
        msg.obj = speedStr;
        mHandler.sendMessage(msg);//更新界面
    }
}
